/**
 * Created by wry on 2015/4/2.
 */
'use strict';

angular.module('backofficeApp.scoreShopManager.controllers', []).
    controller('scoreShopCtrl', ['$scope', '$http', function ($scope, $http) {

        $scope.currentPage = 1;
        $scope.totalPage = 0;
        $scope.pages = [];

        $scope.getGoodsList = function (pageNo) {
            $http.get('http://' + backOfficeHost + '/rest/v1.0/backoffice/score/getScoreShopList/' + pageNo, {//
                headers: {'Content-Type': 'application/json;charset=utf-8'}
            }).success(function (data) {
                $scope.goodsList = [];
                var result = data.data[0];
                result.forEach(function (re) {
                    if (re.images != null)
                        re.imageURL = fastDfsHostIp + re.images;
                    re.createTime = re.create_time;
                    $scope.goodsList.push(re);
                });
                $scope.totalPage = Math.ceil(Number(data.data[1][0].pages) / 10);
            }).error(function () {
            });
        };

        $scope.getGoodsList(1);

        $scope.addGoods = function () {

            $('#goods_modal').modal('show');
            $scope.popupTitle = "添加商品";
            $("#loginId").prop('disabled', false);
            $('#saveButton').show();
            $('#updateButton').hide();
            $('#goodsName').val("");
            $('#goodsDesc').val("");
            $('#inventory').val("");
            $('#price').val("");
            $('#pict').val("");
            $('#pict').attr("required",true);
            $scope.image = null;
            $scope.goods = {};
            $scope.goods.name = "";
            $scope.goods.desc = "";
            $scope.goods.inventory = "";
            $scope.goods.price = "";
        };

        $scope.updateGoods = function (goods) {
            $('#goods_modal').modal('show');
            $scope.popupTitle = "修改商品";
            $("#loginId").prop('disabled', false);
            $('#saveButton').hide();
            $('#updateButton').show();
            $scope.updateId = goods.id;
            $('#goodsName').val(goods.product_name);
            $('#goodsDesc').val(goods.product_desc);
            $('#inventory').val(goods.inventory_level);
            $('#price').val(goods.price);
            $('#pict').val("");
            $('#pict').attr("required",false);
            $scope.image = null;
            $scope.goods = {};
            $scope.goods.name = goods.product_name;
            $scope.goods.desc = goods.product_desc;
            $scope.goods.inventory = goods.inventory_level;
            $scope.goods.price = goods.price;
        };

        $scope.selectFile = function (files) {
            $scope.image = files[0];
        };

        $scope.saveAdd = function (goods, update) {
            if (goods.name == "") {
                return;
            }
            if (goods.desc == "") {
                return;
            }
            if (goods.inventory == "") {
                return;
            }
            if (goods.price == "") {
                //$('#goodsDesc').css("border","1px solid red");
                return;
            }
            if($scope.image == null && update != "update"){
                return;
            }

            var fd = new FormData();
            fd.append('image1', $scope.image);
            fd.append('productName', goods.name);
            fd.append('productDesc', goods.desc);
            fd.append('inventoryLevel', goods.inventory);
            fd.append('price', goods.price);
            if (update == "update") {
                fd.append('cId', $scope.updateId);
            }

            $http.post('http://' + backOfficeHost + '/rest/v1.0/backoffice/score/addOneGoods', fd, {
                transformRequest: angular.identity,
                headers: {'Content-Type': undefined}
            }).success(function (data) {
                $('#goods_modal').modal('hide');
                $scope.getGoodsList($scope.currentPage);
            }).error(function (data) {
            });
        };

        $scope.changeStatus = function (id, status) {

            var input = {
                id: id,
                status: status
            };

            $http.post('http://' + backOfficeHost + '/rest/v1.0/backoffice/score/changeStatus', input, {
                headers: {'Content-Type': 'application/json;charset=utf-8'}
            }).success(function (data) {
                $scope.getGoodsList($scope.currentPage);
            }).error(function (data) {
            });
        };

        $scope.onSelectPage = function (page) {
            $scope.currentPage = page;
            $scope.getGoodsList(page);
        };

        $scope.searchGoods = function(){
            var name = $("#goods_search").val();
            if(name == ""){
                $scope.getGoodsList(1);
                return;
            }
            $http.get('http://' + backOfficeHost + '/rest/v1.0/backoffice/score/searchGoods/'+name, {//
                headers: {'Content-Type': 'application/json;charset=utf-8'}
            }).success(function (data) {
                $scope.goodsList = [];
                var result = data.data;
                result.forEach(function (re) {
                    if (re.images != null)
                        re.imageURL = fastDfsHostIp + re.images;
                    re.createTime = re.create_time;
                    $scope.goodsList.push(re);
                });
                $scope.totalPage = 1;
            }).error(function () {
            });
        }

    }]).
    controller('exchangeRecordCtrl', ['$scope', '$http', function ($scope, $http) {

        $scope.currentPage = 1;
        $scope.totalPage = 1;
        $scope.pages = [];

        $scope.actionList = [
            {
                name: 'bug被采纳',
                action: 8,
                value: 10
            },
            {
                name: '建议被采纳',
                action: 9,
                value: 20
            }
        ];

        $scope.addScore = function (action, userId) {

            if (!action || !userId) {
                return;
            }

            var input = {
                userId: userId,
                userActionType: action
            };

            $http.post('http://' + backOfficeHost + '/rest/v1.0/backoffice/score/addScore', input, {
                headers: {'Content-Type': 'application/json;charset=utf-8'}
            }).success(function (data) {
                $scope.userId = '';
                $scope.action = null;
                if (data.result.status == 0) {
                    alert(data.result.message)
                } else {
                    alert('添加成功！')
                }

            }).error(function (data) {
            });
        };

        $scope.actionList = [
            {
                name: 'bug被采纳',
                action: 8,
                value: 10
            },
            {
                name: '建议被采纳',
                action: 9,
                value: 20
            }
        ];

        $scope.statusSelect = [
            {
                name: '兑换中',
                status: 0
            },
            {
                name: '处理中',
                status: 2
            },
            {
                name: '兑换成功',
                status: 1
            },
            {
                name: '兑换失败',
                status: -1
            }
        ];

        $scope.getExchangeRecord = function (status) {
            var opt = {
                pageNum: $scope.currentPage
            };
            if (status != null) {
                opt.status = status
            }
            $http.post('http://' + backOfficeHost + '/rest/v1.0/backoffice/score/getExchangeRecordList', opt, {
                headers: {'Content-Type': 'application/json;charset=utf-8'}
            }).success(function (data) {
                $scope.totalPage = data.data.pages;
                $scope.exchangeList = [];
                var result = data.data.recordList;
                result.forEach(function (temp) {

                    temp.updateTime = (temp.status == 0 ? temp.createTime : temp.updateTime) * 1000;
                    $scope.exchangeList.push(temp);
                })

            }).error(function (data) {

            });
        };

        $scope.getExchangeRecord(null);

        $scope.onSelectPage = function (page) {
            $scope.currentPage = page;
            $scope.getExchangeRecord($scope.status);
        };


        $scope.examineProduct = function (id, status) {
            var input = {
                orderId: id,
                orderStatus: status
            };

            $http.post('http://' + backOfficeHost + '/rest/v1.0/backoffice/score/examineProduct', input, {
                headers: {'Content-Type': 'application/json;charset=utf-8'}
            }).success(function (data) {
                $scope.getExchangeRecord($scope.status);
            }).error(function (data) {

            });

        }

        $scope.searchGoods = function(){
            var name = $("#goods_search").val();
            if(name == ""){
                return;
            }
            $http.get('http://' + backOfficeHost + '/rest/v1.0/backoffice/score/searchExchangeGoods/'+name, {//
                headers: {'Content-Type': 'application/json;charset=utf-8'}
            }).success(function (data) {
                $scope.exchangeList = [];
                var result = data.data;
                result.forEach(function (temp) {
                    var item = {};
                    item.productName = temp.product_name;
                    item.exchangeNum = temp.exchange_num;
                    item.productPrice = temp.product_price;
                    item.userName = temp.user_name;
                    item.mobile = temp.mobile;
                    item.address = temp.address;
                    item.status = temp.status;
                    item.updateTime = temp.update_time;
                    //temp.updateTime = (temp.status == 0 ? temp.createTime : temp.updateTime) * 1000;
                    $scope.exchangeList.push(item);
                })
                $scope.totalPage = 1;
            }).error(function () {
            });
        }

    }]).
    controller('addScoreCtrl', ['$scope', '$http', function ($scope, $http) {

        $scope.data = {scoreAddRason: '情值商城上线前您赚的情值'};

        $scope.addScoreManual = function (data) {

            data.scoreAddCount = Number(data.scoreAddCount);

            $http.post('http://' + backOfficeHost + '/rest/v1.0/backoffice/score/addScoreManual', data, {
                headers: {'Content-Type': 'application/json;charset=utf-8'}
            }).success(function (data) {
                if (data.result.status == 1) {
                    alert('添加成功');
                    $scope.data = {
                        userId: '',
                        scoreAddCount: '',
                        scoreAddRason: '情值商城上线前您赚的情值'
                    };
                } else {
                    alert('添加失败')
                }
            }).error(function (data) {

            });
        }

    }]).
    controller('addScoreLogCtrl', ['$scope', '$location', '$http', function ($scope, $location, $http) {//TODO: 2015-4-14

        $scope.pages = 0;
        $scope.page = 1;

        $scope.selectPage = function (page) {
            if ($scope.search != null) {
                searchFrontendUser($scope.search.selectedCommunity.objId, $scope.search.mobilePhone, $scope.search.nickName, $scope.search.isVUser, $scope.search.isTalent, page)
            }
        };

        $http.get('http://' + backOfficeHost + '/rest/v1.0/backoffice/user/getAllCommunity', {
            headers: {'Content-Type': 'application/json;charset=utf-8'}
        }).success(function (result) {
            //$scope.search.selectedCommunity = "";
            $scope.communityList = result.data;
        }).error(function () {
        });

        /**
         * 弹出框，修改用户信息
         * @param user
         */
        $scope.saveUserInfo = function (user) {
            var tempUser = {
                nickName: user.nickName,
                roomUnit: user.roomUnit,
                roomNumber: user.roomNumber
            };
            $http.put('http://' + backOfficeHost + '/rest/v1.0/backoffice/user/updateUser/' + user.objId, tempUser, {
                headers: {'Content-Type': 'application/json;charset=utf-8'}
            }).success(function (result) {
                $('#userDetail').modal('hide');
            }).error(function () {
            });
        }

        function searchFrontendUser(communityObjId, mobilePhone, nickName, isVUser, isTalent, currentPage) {

            $scope.showErrorForQueryCondition = false;
            $('#errorMsg').html('');

            if (communityObjId == null) {
                $scope.showErrorForQueryCondition = true;
                $('#errorMsg').html('请选择小区!');
                return;
            }
            if (mobilePhone == null || mobilePhone == '') {
                mobilePhone = 'all';
            }
            if (nickName == null || nickName == '') {
                nickName = 'all';
            }
            if (isVUser == null || isVUser == '') {
                isVUser = 'all';
            }
            if (isTalent == null || isTalent == '') {
                isTalent = 'all';
            }

            var startDate = '';
            if ($("#startDate").val() == null || $("#startDate").val() == '') {
                startDate = '2000-01-01'
            } else {
                startDate = $("#startDate").val();
            }

            var endDate = '';
            if ($("#endDate").val() == null || $("#endDate").val() == '') {
                endDate = '2100-01-01'
            } else {
                endDate = $("#endDate").val();
            }

            if (startDate > endDate) {
                $scope.showErrorForQueryCondition = true;
                $('#errorMsg').html('起始日期不能大于终止日期!');
                return;
            }

            var pageSize = 20;
            var startRowNo = (currentPage - 1) * pageSize;

            //找出该小区的所有用户
            /* TODO: URL切换--//new：切换到“积分搜索”， //old：从原来的“用户搜索”*/
            //$http.get('http://' + backOfficeHost + '/rest/v1.0/backoffice/user/searchFrontendUser/' + communityObjId + '/' + mobilePhone + '/' + nickName + '/' + isVUser + '/' + isTalent + '/' + startDate + '/' + endDate + '/' + startRowNo + '/' + pageSize, {
            $http.get('http://' + backOfficeHost + '/rest/v1.0/Score/user/searchFrontendUser/' + communityObjId + '/' + mobilePhone + '/' + nickName + '/' + isVUser + '/' + isTalent + '/' + startDate + '/' + endDate + '/' + startRowNo + '/' + pageSize, {
                headers: {'Content-Type': 'application/json;charset=utf-8'}
            }).success(function (result) {
                $scope.userList = result.data;
                $scope.pages = 10;
                $scope.userList.items.forEach(function (elem) {
                    if (elem.mobilePhone != null && elem.mobilePhone != '') {
                        elem.source = '手机';
                    } else {
                        if (elem.wechatId != null && elem.wechatId != '') {
                            if (elem.wechatId.substring(0, 2) == 'oW') {
                                elem.source = '微信';
                            } else {
                                elem.source = 'QQ';
                            }
                        } else {
                            elem.source = '未知';
                        }
                    }
                });
            }).error(function () {
            });
        }


        /**
         * 查询小区的所有用户
         * @param communityObjId
         * @param mobilePhone
         * @param nickName
         */
        $scope.searchUser = function (communityObjId, mobilePhone, nickName, isVUser, isTalent) {
            searchFrontendUser(communityObjId, mobilePhone, nickName, isVUser, isTalent, 1);

            /*TODO:*/
            getUserScoreAddRecord();
        };


        /**
         * TODO:获取积分增加记录 2015-4-14
         */
        function getUserScoreAddRecord() {
            //$http.get('http://' + backOfficeHost + '/rest/v1.0/Score/getUserScoreAddRecord/1/54db1a1816d9f5f3652a4cbb/54db1a1816d9f5f3652a4cbb/', {
            $http.get('http://' + backOfficeHost + '/rest/v1.0/Score/getUserScoreAddRecord/1/48/48/', {
                /*TODO：用到是我本地数据库的数据源测试的， */
                headers: {'Content-Type': 'application/json;charset=utf-8'}
            }).success(function (result) {
                $scope.getUserScoreAddRecord_result = result.data;
                $scope.getUserScoreAddRecord_result11 = 10;
                /*$scope.userList.items.forEach(function (elem) {
                 if (elem.mobilePhone != null && elem.mobilePhone != '') {
                 elem.source = '手机';
                 } else {
                 if (elem.wechatId != null && elem.wechatId != '') {
                 if (elem.wechatId.substring(0, 2) == 'oW') {
                 elem.source = '微信';
                 } else {
                 elem.source = 'QQ';
                 }
                 } else {
                 elem.source = '未知';
                 }
                 }
                 });*/
            }).error(function () {
            });
        }


        /**
         * 下拉框选择小区
         */
        $scope.selectCommunity = function () {
            $scope.showErrorForQueryCondition = false;
        }

        /**
         * 获取用户详细信息
         * @param user
         */
        $scope.goDetail = function (user) {
            $('#userDetail').modal('show');
            $scope.userDetail = user;
        }

        /**
         * 弹出黑白操作框
         * @param user
         */
        $scope.blackListConfig = function (user, type) {
            $('#user_modal').modal('show');
            $scope.toBeBlackListUserObjId = user.objId;
            $scope.toBeBlackListUserNickName = user.nickName;
            $("#nickName").prop('disabled', false);

            //拉黑用户，需要显示原因
            if (type == 0) {
                $scope.popupTitle = "把该用户拉黑...";
                $('#reasonInput').show();
                $scope.toBeBlackListUserFrozen = true;
                $scope.toBeBlackListUserReason = null;
                $('#saveButton').text('设置黑名单');
            }
            else {
                $scope.popupTitle = "把该用户拉白...";
                $('#reasonInput').hide();
                $scope.toBeBlackListUserFrozen = false;
                $scope.toBeBlackListUserReason = ' ';
                $('#saveButton').text('设置白名单');
            }
        };

        /**
         * 把用户设置为VUser，或者取消VUser
         */
        $scope.setOrCancelVUser = function (user, messageTitle, authenticationStatus) {
            var tempValue = {
                authenticationStatus: authenticationStatus
            }
            bootbox.confirm(messageTitle, function (result) {
                if (result == true) {
                    $http.post('http://' + backOfficeHost + '/rest/v1.0/backoffice/user/setCancelVUser/' + user.objId + '/' + user.community.objId, tempValue, {
                        headers: {'Content-Type': 'application/json;charset=utf-8'}
                    }).success(function (result) {
                        $scope.userList.items.forEach(function (elem) {
                            if (elem.objId == user.objId) {
                                elem.authenticationStatus = tempValue.authenticationStatus;
                            }
                        });
                    }).error(function () {
                    });
                }
            }).find("div.modal-dialog").css({width: '30%'});
        }

        /**
         * 升级为达人，或者取消达人
         * @param user
         * @param messageTitle
         * @param type
         */
        $scope.setOrCancelTalent = function (user, messageTitle, type) {
            if (type == '1') {
                bootbox.prompt(messageTitle, function (result) {
                    if (result != null && result != '') {
                        $http.get('http://' + backOfficeHost + '/rest/v1.0/backoffice/user/setCancelFrontendUserToTalent/' + user.objId + '/' + result + '/' + +type, {
                            headers: {'Content-Type': 'application/json;charset=utf-8'}
                        }).success(function (result) {
                            $scope.userList.items.forEach(function (elem) {
                                if (elem.objId == user.objId) {
                                    if (type == '1') {
                                        elem.userType = 'Talent';
                                    } else {
                                        elem.userType = 'normalAppUser';
                                    }
                                }
                            });
                        }).error(function () {
                        });
                    }
                }).find("div.modal-dialog").css({width: '30%'});
            } else {
                bootbox.confirm(messageTitle, function (result) {
                    if (result != null && result != '') {
                        $http.get('http://' + backOfficeHost + '/rest/v1.0/backoffice/user/setCancelFrontendUserToTalent/' + user.objId + '/ /' + +type, {
                            headers: {'Content-Type': 'application/json;charset=utf-8'}
                        }).success(function (result) {
                            $scope.userList.items.forEach(function (elem) {
                                if (elem.objId == user.objId) {
                                    if (type == '1') {
                                        elem.userType = 'Talent';
                                    } else {
                                        elem.userType = 'normalAppUser';
                                    }
                                }
                            });
                        }).error(function () {
                        });
                    }
                }).find("div.modal-dialog").css({width: '30%'});
            }
        }

        /**
         * 保存黑白操作设置
         * @param userObjId
         * @param toBeBlackListUserFrozen
         * @param reason
         */
        $scope.saveBlackListOrWhiteList = function (userObjId, toBeBlackListUserFrozen, reason) {
            if (toBeBlackListUserFrozen == true) {
                var tempFrozenReason = {
                    frozenOrNot: true,
                    reason: reason
                }
                if (reason == null || reason == '') {
                    return;
                }
            } else {
                var tempFrozenReason = {
                    frozenOrNot: false,
                    reason: reason
                }
            }

            $http.post('http://' + backOfficeHost + '/rest/v1.0/backoffice/user/putFrontendUserToBlackList/' + userObjId, tempFrozenReason, {
                headers: {'Content-Type': 'application/json;charset=utf-8'}
            }).success(function (result) {
                $('#user_modal').modal('hide');
                $scope.userList.items.forEach(function (elem) {
                    if (elem.objId == userObjId) {
                        elem.frozenOrNot = tempFrozenReason.frozenOrNot;
                        elem.reason = tempFrozenReason.reason;
                    }
                });
            }).error(function () {
            });
        }
    }]).
    controller('scoreShopSearchValueCtrl', ['$scope', '$http','CommunityService', function ($scope, $http,communityService) {

        $scope.currentPage = 1;
        $scope.totalPage = 0;
        $scope.pages = [];
        $scope.communityList = communityService.getAllCommunityService();

        $scope.getAtList = function (input) {
            if (!input||input.communityName == null) {
                return;
            }
            if (!input||input.userName == null) {
                return;
            }
            $http.post('http://' + backOfficeHost + '/rest/v1.0/backoffice/score/searchValue', input, {
                headers: {'Content-Type': 'application/json;charset=utf-8'}
            }).success(function (data) {
                $scope.resultList = data.data;
                $scope.totalPage = 1;
            }).error(function (data) {
            });
        };
        $scope.onSelectPage = function (page) {
            $scope.currentPage = page;
            $scope.getGoodsList(page);
        };
        $scope.getGoodsList = function(page){
            $http.get('http://' + backOfficeHost + '/rest/v1.0/backoffice/score/getCommunityScoreList/' + $scope.input.communityName+'/'+page, {//
                headers: {'Content-Type': 'application/json;charset=utf-8'}
            }).success(function (data) {
                $scope.resultList = data.data.data;
                $scope.totalPage = Math.ceil(Number(data.data.pages)/10);
            }).error(function () {
            });
        }
    }]).
    directive('paging', function () {
        return {
            restrict: 'E',
            //scope: {
            //    numPages: '=',
            //    currentPage: '=',
            //    onSelectPage: '&'
            //},
            template: '',
            replace: true,
            link: function (scope, element, attrs) {
                scope.$watch('currentPage', function (value) {
                    scope.pages = [];
                    for (var i = value - 5 > 0 ? value - 5 : 1; i <= (value + 5 > scope.totalPage ? scope.totalPage : value + 5); i++) {
                        scope.pages.push(i);
                    }
                });
                scope.$watch('totalPage', function (value) {
                    scope.pages = [];
                    for (var i = scope.currentPage - 5 > 0 ? scope.currentPage - 5 : 1; i <= (scope.currentPage + 5 > value ? value : scope.currentPage + 5); i++) {
                        scope.pages.push(i);
                    }
                });

                scope.isActive = function (page) {
                    return scope.currentPage === page;
                };
                scope.selectPage = function (page) {
                    if (!scope.isActive(page)) {
                        scope.currentPage = page;
                        scope.onSelectPage(page);
                    }
                };
                scope.selectPrevious = function () {
                    if (!scope.noPrevious()) {
                        scope.selectPage(scope.currentPage - 1);
                    }
                };
                scope.selectNext = function () {
                    if (!scope.noNext()) {
                        scope.selectPage(scope.currentPage + 1);
                    }
                };
                scope.noPrevious = function () {
                    return scope.currentPage == 1;
                };
                scope.noNext = function () {
                    return scope.currentPage == scope.totalPage;
                };

            }
        };
    });